<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\AntisepticRequest;
use App\Models\Antiepidemic;
use App\Models\Category;
use App\Models\Config;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use zgldh\QiniuStorage\QiniuStorage;

class AntisepticController extends Controller
{
    public function index($id)
    {
        $cate = Category::find($id);
        $disk = QiniuStorage::disk('qiniu');
        $token = $disk->uploadToken();  //获取上传Token
        return view('index', ['token' => $token, 'cate' => $cate]);
    }

    /**
     * @throws \Exception
     */
    public function store(AntisepticRequest $request): \Illuminate\Http\JsonResponse
    {
        $input = $request->only(["studentName", "studentSex", "school", "grade", "parentName", "phone", "address", "healthCodeList", "tourCodeList", "identityList", 'category_id']);
        $category = Category::query()->find($input['category_id']);
        if ($category['end_time'] < Carbon::now()->toDateString()) {
            return response()->json([
                'status' => false,
                'message' => '已过期',
                'code' => '500'
            ]);
        }
        DB::beginTransaction();
        try {
            $input['healthCodeList'] = json_encode($input['healthCodeList']);
            $input['tourCodeList'] = json_encode($input['tourCodeList']);
            $input['identityList'] = json_encode($input['identityList']);
            $res = Antiepidemic::query()->create($input);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return response()->json($res);
    }
}
